package com.travel.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.travel.entity.Admin;
import com.travel.service.AdminService;
import com.travel.service.impl.AdminServiceImpl;

/**
 * Servlet implementation class AdminServlet
 */
@WebServlet("/admin")
public class AdminServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private AdminService adminService =new AdminServiceImpl();  
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AdminServlet() {
        super();
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//使用标识符来区分不同的请求
		String op = request.getParameter("op");
		if ("adminLogin".equals(op)) {
			//接收登录请求
			doLogin(request,response);
		}else if ("adminLogout".equals(op)) {
			doLogout(request,response);
		}
	}

	private void doLogout(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 请求session中指定的属性
		HttpSession session= request.getSession();
		session.removeAttribute("admin");
		
        // 重定向登录页面
		response.sendRedirect("back/login.jsp");
	}

	private void doLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setCharacterEncoding("UTF-8");
		//调度,调用业务层
		String adminName = request.getParameter("username");
		String adminPassword = request.getParameter("password");
		List<Admin> list = adminService.login(adminName, adminPassword);
		if (!list.isEmpty()) {
			//登录成功,存储数据到session会话作用域
			HttpSession session = request.getSession();
			session.setAttribute("admin", list.get(0));
			
			//判断是否记住密码
			String remember = request.getParameter("remember");
			
			//将用户信息存储到cookie中,存储方式username=password
			Cookie cookie = new Cookie(adminName, adminPassword);
			
			if ("on".equals(remember)) {
				
				cookie.setMaxAge(60*60*24);
				//添加到HTTP的响应体中
				response.addCookie(cookie);
			}else {
				//选择不记住密码
				//将当前用户的cookie信息删除
				cookie.setMaxAge(0);
				response.addCookie(cookie);
			}
			//跳转到首页
			response.sendRedirect("back/index.jsp");
		}else {
			//登录失败,跳转到登录界面
			response.sendRedirect("back/login.jsp?loginErrorMessage=error");
		}
	}

}
